<template>
  <div>
    <a-dropdown class="btn-chose-site" :trigger="['click']">
      <a class="ant-dropdown-link" @click="e => e.preventDefault()">
        <a-tooltip placement="left">
          <template slot="title">
            <span>点击切换站点</span>
          </template>
          <a-button type="primary" icon="setting" />
        </a-tooltip>
      </a>
      <a-menu slot="overlay">
        <a-menu-item
          v-for="item in siteArray"
          :key="item.id"
          :class="['site-item', (item.id === currentEditSiteId ? 'active' : '')]"
          :value="item.id"
          @click="setCurrentSite(item.id)">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-dropdown>
  </div>
</template>

<script>
import { getCurrentEditSiteId, selectSitesByUserId, setCurrentEditSiteId } from '@/api/cms/site/user'

export default {
  name: 'CmsChoseSite',
  data () {
    return {
      currentEditSiteId: null,
      siteArray: []
    }
  },
  mounted () {
    this.loadCurrentEditSiteId()
    this.loadSitesByUserId()
  },
  methods: {
    /**
     * 加载当前登录用户拥有的站点列表
     */
    loadSitesByUserId () {
      selectSitesByUserId().then(({ data }) => {
        this.siteArray = data
      })
    },
    loadCurrentEditSiteId () {
      getCurrentEditSiteId().then(({ data }) => {
        this.currentEditSiteId = data
      })
    },
    setCurrentSite (siteId) {
      setCurrentEditSiteId(siteId).then(res => {
        this.currentEditSiteId = siteId
        this.$emit('change')
      })
    }
  }
}
</script>

<style lang='less' scoped>
@import '~ant-design-vue/es/style/themes/default.less';

.btn-chose-site {
  position: absolute;
  top: -16px;
  right: -16px;

  .ant-btn {
    border-radius: 0 0 0 50%;
  }
}

.site-item.active {
  color: #fff;
  background-color: @primary-color;
}
</style>
